// 检查是否需要登录
export function checkNeedLogin() {
  const app = getApp()
  return !app.globalData.isLoggedIn
}

// 登录提示对话框
export function showLoginModal() {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title: '提示',
      content: '请先登录后再操作',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          const app = getApp()
          app.login()
            .then(resolve)
            .catch(reject)
        } else {
          reject(new Error('用户取消登录'))
        }
      }
    })
  })
}

// 登录检查装饰器
export function requireLogin() {
  return function(target, name, descriptor) {
    const original = descriptor.value
    descriptor.value = async function(...args) {
      if (checkNeedLogin()) {
        try {
          await showLoginModal()
        } catch (error) {
          console.log('用户取消登录')
          return
        }
      }
      return original.apply(this, args)
    }
    return descriptor
  }
}

// 检查登录状态并提示
export function checkLogin() {
  const app = getApp()
  if (!app.globalData.isLoggedIn) {
    wx.showModal({
      title: '提示',
      content: '请先登录后再操作',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/my/my'
          })
        }
      }
    })
    return false
  }
  return true
} 